package com.ruoyi.framework.tree;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.domain.server.TreeSelectArea;
import com.ruoyi.framework.web.domain.server.TreeSelectVO;
import com.ruoyi.project.configureSystem.domain.SysArea;
import com.ruoyi.project.configureSystem.domain.SysNode;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class TreeUtils {
    public  List<TreeSelectVO> buildTreeSelect(List<SysNode> nodes) {
        List<SysNode> nodeTrees = buildTree(nodes);
        return nodeTrees.stream().map(TreeSelectVO::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param
     * @return 树结构列表
     */
    public List<SysNode> buildTree(List<SysNode> nodes) {
        List<SysNode> returnList = new ArrayList<SysNode>();
        List<String> tempList = new ArrayList<String>();
        for (SysNode node : nodes) {
            tempList.add(node.getNodeId());
        }
        for (Iterator<SysNode> iterator = nodes.iterator(); iterator.hasNext(); ) {
            SysNode node = (SysNode) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(node.getParentId())) {
                recursionFn(nodes, node);
                returnList.add(node);
            }
        }
        if (returnList.isEmpty()) {
            returnList = nodes;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysNode> list, SysNode t) {
        // 得到子节点列表
        List<SysNode> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysNode tChild : childList) {
            if (hasChild(list, tChild)) {
                // 判断是否有子节点
                Iterator<SysNode> it = childList.iterator();
                while (it.hasNext()) {
                    SysNode n = (SysNode) it.next();
                    recursionFn(list, n);
                }
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysNode> getChildList(List<SysNode> list, SysNode t)
    {
        List<SysNode> tlist = new ArrayList<SysNode>();
        Iterator<SysNode> it = list.iterator();
        while (it.hasNext())
        {
            SysNode n = (SysNode) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().equals(t.getNodeId()))
            {
                tlist.add(n);
            }
        }
        return tlist;
    }


    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysNode> list, SysNode t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
